package
{
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	public class CDSprite extends Sprite
	{
		public static const PI_RADIUS:Number = Math.PI / 180;
		public static const LEFT :Number = 180 * PI_RADIUS;
		public static const BOTTOM : Number = 90 * PI_RADIUS;
		public static const RIGTH : Number = 0;
		public static const TOP : Number = 270 * PI_RADIUS;
		
		private var _color:uint;
		private var _radius:uint;
		private var _dir:Number;
		
		private var _timer:Timer;
		private var _startTime:int;
		private var _rad:Number;
		
		private var _sprite:Sprite;
		
		public function CDSprite(color:uint,radius:uint,dir:Number = TOP,rectMask:Rectangle = null)
		{
			super();
			this.mouseChildren = false;
			this.mouseEnabled = false;
			
			this._color = color;
			this._radius = radius;
			this._dir = dir;
			
			rectMask = new Rectangle(0,0,50,50);
			
			if( rectMask )
			{
				_sprite = new Sprite;
				addChild( _sprite );
				
				var shape:Shape = new Shape;
				shape.graphics.lineStyle(1,0);
				shape.graphics.beginFill(0);
				shape.graphics.drawRect(-rectMask.width/2,-rectMask.height/2,rectMask.width,rectMask.height);
				shape.graphics.endFill();
				addChild( shape );
							
				_sprite.mask = shape;
			}
			
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER,onTimerHandler);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE,onTimerCompleteHandler);
		}
		
		protected function onTimerCompleteHandler(event:TimerEvent):void
		{
			setTimeout(function():void
			{
				var _graphics:Graphics = _sprite?_sprite.graphics:graphics;
				_graphics.clear();
			},100);
		}
		
		protected function onTimerHandler(event:TimerEvent):void
		{
			var radians:Number = _timer.currentCount * _rad + _dir;
			
			drawCD( radians,_sprite?_sprite.graphics:this.graphics);
		}
		
		private function drawCD(radians,graphics:Graphics):void
		{
			var x:Number = Math.cos( radians ) * _radius;
			var y:Number =  Math.sin( radians ) * _radius;
			
			graphics.lineTo( x, y);
		}
		
		public function start(time:uint):void
		{
			var graphics:Graphics = _sprite?_sprite.graphics:this.graphics;
			graphics.clear();
			graphics.lineStyle(1,_color);
			graphics.beginFill(_color);
			drawCD( _dir,graphics );
			
			_startTime = getTimer();
			_rad = (360/60) * PI_RADIUS;
				
			_timer.reset();
			_timer.delay = time / 60;
			_timer.repeatCount = 60;
			_timer.start();
		}
		
	}
}